import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import QThread
from PySide2.QtUiTools import QUiLoader
from PyQt5.QtWidgets import QApplication, QMessageBox, QTableWidgetItem
from GetHostIP import HostIP
import socket


class Stats:
    def __init__(self):
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        # http://www.b520.cc/2_2157/
        self.ui = QUiLoader().load('ui/appui2.ui')
        ip = HostIP().ip
        self.HPortStatus = 0
        self.DIPStatus = 0
        self.DPortStatus = 0

        self.ui.setWindowTitle("网络调试助手")
        self.ui.pushButton_2.setEnabled(False)  # 发送
        # self.ui.pushButton_3.setEnabled(False)  # 连接
        self.ui.pushButton_4.setEnabled(False)  # 保存
        self.ui.lineEdit.setText(ip)
        self.ui.pushButton_3.clicked.connect(self.establishConnection)
        self.ui.pushButton_2.clicked.connect(self.sendData)

    def clearTextBrowser(self):
        self.ui.textBrowser.clear()

    def clearLineText(self):
        self.ui.lineEdit_5.clear()

    def infoCompleted(self):
        self.isHostPort()
        self.isDestPort()
        self.isDestIP()
        if self.HPortStatus * self.DPortStatus * self.DIPStatus == 1:
            return True
        return False

    def establishConnection(self):
        print(self.infoCompleted())
        if self.infoCompleted():
            self.ui.pushButton_2.setEnabled(True)
            self.ui.textBrowser.append("OK")


    def isHostPort(self):
        host_port = self.ui.lineEdit_2.text()
        if host_port is not None and host_port != '':
            self.HPortStatus = 1

    def isDestPort(self):
        dest_port = self.ui.lineEdit_3.text()
        if dest_port is not None and dest_port != '':
            self.DPortStatus = 1

    def isDestIP(self):
        dest_ip = self.ui.lineEdit_4.text()
        if dest_ip is not None and dest_ip != '':
            self.DIPStatus = 1

    def sendData(self):
        self.host_ip = self.ui.lineEdit.text()
        self.host_port = int(self.ui.lineEdit_2.text())
        self.dest_ip = self.ui.lineEdit_4.text()
        self.dest_port = int(self.ui.lineEdit_3.text())

    def recvData(self, info):
        self.ui.textBrowser.append(info+'\n')


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    stats = Stats()
    stats.ui.show()
    app.exec_()